#
# This file is part of the kernelstudio package.
#
# (c) 2014-2025 zlin <admin@kernelstudio.com>
#
# For the full copyright and license information, please view the LICENSE file
# that was distributed with this source code.
import datetime
import uuid

from ksai.models.document_category import DocumentCategoryModelQuery, DocumentCategoryModel
from ksai.persistence.database import db
from ksai.utils.strings import has_text


class DocumentCategoryService:

    @staticmethod
    def find_by_query(query: DocumentCategoryModelQuery) -> DocumentCategoryModelQuery:
        q = DocumentCategoryModel.query.filter(DocumentCategoryModel.deleted_at == None)
        if has_text(query.keyword):
            search = f"%{query.keyword}%"
            q = q.filter(
                db.or_(
                    DocumentCategoryModel.name.ilike(search),
                )
            )
        items = q.paginate(page=query.page, per_page=query.offset, error_out=False)
        query.pagination(items)
        return query

    @staticmethod
    def find_one_by_uuid(uuid_param: str) -> DocumentCategoryModel:
        q = DocumentCategoryModel.query.filter(DocumentCategoryModel.deleted_at == None)
        return q.filter_by(uuid=str(uuid_param)).first()

    @staticmethod
    def exists(category: DocumentCategoryModel) -> bool:
        q = DocumentCategoryModel.query.filter(DocumentCategoryModel.deleted_at == None)
        q = q.filter(
            DocumentCategoryModel.name == category.name,
            DocumentCategoryModel.code == category.code,
            DocumentCategoryModel.uuid != category.uuid
        )
        return q.first() is not None

    @staticmethod
    def save(category: DocumentCategoryModel) -> bool:
        if category.uuid is None:
            category.uuid = str(uuid.uuid4())
        if category.created_at is None:
            category.created_at = datetime.datetime.now()
        if category.updated_at is None:
            category.updated_at = datetime.datetime.now()

        if DocumentCategoryService.exists(category):
            raise ValueError("分类已经存在.")

        db.session.add(category)
        db.session.commit()
        return True
